#ifdef _DEBUG
#include "common.h"
#include <commctrl.h>

#include "infoform.h"
#include "mapform.h"

#include "debugdialog.h"

#ifdef _DEBUG
#define DEBUG_NEW new( _NORMAL_BLOCK, __FILE__, __LINE__ )
#define new DEBUG_NEW
#endif

LRESULT CALLBACK DebugDialogProc( HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam )
{
	Core& core = Core::GetInstance();
	switch( msg )
	{
	case WM_NOTIFY :
		if( ( ( LPNMHDR )lParam )->code == TCN_SELCHANGE )
		{
			HWND hTab = core.GetDebugDialog()->GetTabCtrlHandle();
			core.GetDebugDialog()->ActivateTab( TabCtrl_GetCurSel( hTab ) );
		}
		break;
	case WM_DESTROY :
		break;
	}
	return false;
}

DebugDialog::DebugDialog()
:	_hWnd( NULL )
,	_hTabCtrl( NULL )
,	_pInfoForm( NULL )
,	_pMapForm( NULL )
{
	_hWnd = CreateDialog( 
		Core::GetInstance().GetInstanceHandle(),
		( LPCWSTR )IDD_DEBUGDIALOG,
		Core::GetInstance().GetWindowHandle(),
		( DLGPROC )DebugDialogProc );

	RECT mainRect = {0,};
	RECT dbgRect = {0,};
	GetWindowRect( Core::GetInstance().GetWindowHandle(), &mainRect );
	GetWindowRect( _hWnd, &dbgRect );
	SetWindowPos( 
		_hWnd, HWND_TOP, mainRect.right, mainRect.top,
		dbgRect.right-dbgRect.left, dbgRect.bottom-dbgRect.top,
		0 );

	ShowWindow( _hWnd, SW_SHOW );

	// Tab control
	LPWSTR tabName[TAB_MAX] = 
	{
		L"info",
		L"map",
	};

	_hTabCtrl = GetDlgItem( _hWnd, IDC_MAINTABCTRL );

	TCITEM tie;
	tie.mask = TCIF_TEXT | TCIF_IMAGE;
	for( int i = 0; i < TAB_MAX; ++i )
	{
		tie.pszText = tabName[i];
		TabCtrl_InsertItem( _hTabCtrl, i, &tie );
	}

	// Forms
	_pInfoForm = new InfoForm( TAB_INFO, _hTabCtrl );
	_formHandles.push_back( _pInfoForm->GetWindowHandle() );

	_pMapForm = new MapForm( TAB_MAP, _hTabCtrl );
	_formHandles.push_back( _pMapForm->GetWindowHandle() );

	ActivateTab( 0 );
}

DebugDialog::~DebugDialog()
{
	if( _pInfoForm )
	{
		delete _pInfoForm;
		_pInfoForm = NULL;
	}
	if( _pMapForm )
	{
		delete _pMapForm;
		_pMapForm = NULL;
	}
}

void DebugDialog::ActivateTab( int index )
{
	assert( _formHandles.size() == TAB_MAX );

	for( int i = 0; i < TAB_MAX; ++i )
	{
		int op = ( i == index )? SW_SHOW : SW_HIDE;
		ShowWindow( _formHandles[i], op );
	}
}

void DebugDialog::ResetDialogPos()
{
	RECT mainRect = {0,};
	RECT dbgRect = {0,};
	GetWindowRect( Core::GetInstance().GetWindowHandle(), &mainRect );
	GetWindowRect( _hWnd, &dbgRect );
	SetWindowPos( 
		_hWnd, HWND_TOP, mainRect.right, mainRect.top,
		dbgRect.right-dbgRect.left, dbgRect.bottom-dbgRect.top,
		0 );
}

void DebugDialog::SetFPS( float fps )
{
	if( fps > 10000.0f )
	{
		return;
	}
	sprintf_s( _fps, sizeof( _fps ), "%.2f", fps );
	SetDlgItemTextA( _hWnd, IDC_EDIT_FPS, _fps );
}

void DebugDialog::SetLevelInfos( Level* pLevel )
{
	_pInfoForm->SetInfos( pLevel );
}

void DebugDialog::SetMapInfo( const MAP_DESC& desc )
{
	_pMapForm->SetMap( desc.ppMap, desc.nGrid );
}

#endif